use super::into_iter::IntoIter;
use crate::deque::iter::Iter;
use crate::deque::iter_mut::IterMut;

#[derive(Debug)]
pub struct Deque<T> {
    pub cap: usize,
    pub data: Vec<T>,
}

impl<T> Deque<T> {
    pub fn new(cap: usize) -> Self {
        Self {
            cap,
            data: Vec::with_capacity(cap),
        }
    }

    pub fn is_empty(&self) -> bool {
        self.data.len() == 0
    }

    pub fn is_full(&self) -> bool {
        self.cap == self.data.len()
    }

    pub fn len(&self) -> usize {
        self.data.len()
    }
    pub fn clean(&mut self) {
        self.data = Vec::with_capacity(self.cap);
    }

    pub fn add_front(&mut self, item: T) -> Result<(), String> {
        if self.len() == self.cap {
            return Err("No space available".to_string());
        }
        self.data.push(item);
        Ok(())
    }

    pub fn add_rear(&mut self, item: T) -> Result<(), String> {
        if self.len() == self.cap {
            return Err("No space available".to_string());
        }
        self.data.insert(0, item);
        Ok(())
    }

    pub fn remove_front(&mut self) -> Option<T> {
        if self.len() > 0 {
            self.data.pop()
        } else {
            None
        }
    }

    pub fn remove_rear(&mut self) -> Option<T> {
        if self.len() > 0 {
            Some(self.data.remove(0))
        } else {
            None
        }
    }

    //以下为双端队列实现的迭代器功能
    //into_iter: 双端队列改变，成为迭代器
    //iter: 双端队列不变，只得到不可变迭代器
    //iter_mut: 双端队列不变，得到可变迭代器
    fn into_iter(self) -> IntoIter<T> {
        IntoIter::new(self)
    }

    fn iter(&self) -> Iter<T> {
        let mut iterator = Iter { stack: Vec::new() };
        for item in self.data.iter() {
            iterator.stack.push(item);
        }
        iterator
    }

    fn iter_mut(&mut self) -> IterMut<T> {
        let mut iterator = IterMut { stack: Vec::new() };
        for item in self.data.iter_mut() {
            iterator.stack.push(item);
        }
        iterator
    }
}
